package com.building.hcrm.common;

import java.io.StringReader;
import java.net.HttpURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;

import com.building.hcrm.R;

import android.content.Context;
import android.util.Xml;

public class HttpHelper
{
	private static HttpHelper _instance;

	public static HttpHelper getInstance(Context context)
	{
		if (_instance == null)
		{
			_instance = new HttpHelper(context);
		}
		return _instance;
	}

	private Context _context;
	
	public HttpHelper(Context context)
	{
		_context = context;
	}

	public String HttpPost(String Url, String strMethodName, String strPost) throws Exception
	{
		String strReturn = "";
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = null;
		HttpEntity resEntity = null;
		try
		{
			HttpParams httpparams = httpclient.getParams();
			// 设置连接超时
			HttpConnectionParams.setConnectionTimeout(httpparams, ComConst.CONNECT_TIME_OUT);
			// 设置获取服务器回复超时
			HttpConnectionParams.setSoTimeout(httpparams, ComConst.READ_TIME_OUT);
			HttpPost httppost = new HttpPost(Url + "/" + strMethodName);
			// 添加http头信息
			httppost.addHeader("Content-Type", "application/json");
			if(null != strPost && 0<strPost.length())
				httppost.setEntity(new StringEntity(strPost, "UTF-8"));

			response = httpclient.execute(httppost);
			// 检验状态码，如果成功接收数据
			int code = response.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_OK)
			{
				resEntity = response.getEntity();
				strReturn = EntityUtils.toString(resEntity);
			}
			else
			{
				throw new Exception(_context.getResources().getString(R.string.ex_server_return_error));
			}
		}
		catch (Exception e)
		{
			throw new Exception(_context.getResources().getString(R.string.ex_connect_error),e);
		}
		finally
		{
			httpclient.getConnectionManager().shutdown();
		}
		return strReturn;
	}
}
